<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
			<el-form-item label="名称" prop="name">
				<el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="分类" prop="categoryId">
				<el-cascader :props="{label:'name',value:'id',checkStrictly: false}" v-model="categoryId" :options="articleCategoryList" @change="handleQuery"></el-cascader>

			</el-form-item>
			<el-form-item label="状态" prop="categoryId">
				<el-select v-model="queryParams.status" filterable placeholder="请选择状态" clearable @change="handleQuery">
					<el-option label="已下架" :value="0"></el-option>
					<el-option label="已上架" :value="1"></el-option>
				</el-select>
			</el-form-item>

			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['biz:deduction:goods:add']">新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['biz:deduction:goods:edit']">修改</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['biz:deduction:goods:remove']">删除</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['biz:deduction:goods:export']">导出</el-button>
			</el-col>
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange" row-key='id'>
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="图片" align="center" prop="imgUrl" width="100">
				<template slot-scope="scope">
					<div v-if="scope.row.imgUrl">

						<img v-if="scope.row.imgUrl.indexOf('http') == -1" :src="$store.state.app.imgUrl +scope.row.imgUrl" style="width:100px" alt="">
						<img v-else :src="scope.row.imgUrl" style="width:100px" alt="">
					</div>
				</template>
			</el-table-column>
			<el-table-column label="主键" align="center" prop="id" />
			<el-table-column label="名称" align="center" prop="name" />
			<el-table-column label="门店名称" align="center" prop="storeName" />
			<el-table-column label="分类" align="center" prop="categoryName" />
			<el-table-column label="库存" align="center" prop="stock" />
			<el-table-column label="单位" align="center" prop="unit" />
			<el-table-column label="价格" align="center" prop="" width="300px">
				<template slot-scope="scope">
					<div>
						<div>原价：￥{{scope.row.originalPrice||0}}</div>
						<div>会员价：￥{{scope.row.preferentialPrice||0}}</div>

					</div>
				</template>
			</el-table-column>

			<el-table-column label="排序" align="center" prop="sort" />
			<el-table-column label="已售数量" align="center" prop="soldQuantity" />
			<el-table-column label="备注" align="center" prop="remark" />
			<el-table-column label="创建时间" align="center" prop="createTime" width='150' />

			<el-table-column label="状态" prop="statusName" width='100' fixed='right'>
				<template slot-scope="scope">
					<div class="flex-center">
						<el-tag :type="scope.row.status =='1'?'success':'danger' ">{{scope.row.status?'已上架':'已下架'}}</el-tag>
						<!-- <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch> -->
					</div>
				</template>
			</el-table-column>
			<el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width" >
				<template slot-scope="scope">
					<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['biz:deduction:goods:edit']">修改</el-button>
					<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['biz:deduction:goods:remove']">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

		<!-- 添加或修改biz_商品管理对话框 -->
		<el-dialog :title="title" :visible.sync="open" :close-on-click-modal='false'width="80%" append-to-body>

			<el-form ref="form" :model="form" :rules="rules" label-width="80px">
				<el-form-item label="名称" prop="name">
					<el-input v-model="form.name" placeholder="请输入名称" />
				</el-form-item>
				<el-form-item label="分类">
					<el-cascader :props="{label:'name',value:'id'}" v-model="form.categoryId" :options="articleCategoryList" @change="handleChange"></el-cascader>
				</el-form-item>
				<el-form-item label="门店" prop="name">
					<el-select :loading="loading" :remote-method="remoteMethod" clearable="" remote filterable v-model="form.storeId" placeholder="请选择">
						<el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="库存" prop="stock">
					<el-input v-model="form.stock" type="number" placeholder="请输入库存" />
				</el-form-item>
				<el-form-item label="单位" prop="unit">
					<el-input v-model="form.unit" placeholder="请输入单位" />
				</el-form-item>
				<el-form-item label="状态" prop="unit">
					<el-switch v-model="form.status" active-text="上架" inactive-text="下架" :active-value="1" :inactive-value="0">
					</el-switch>
				</el-form-item>
				<el-card style="margin-bottom:20px">
					<h1>价格</h1>
					<div>
						<div class="flex-row" style="margin-bottom:20px">
							<div style="margin-right:20px">已售数量：{{form.soldQuantity}}</div>
						</div>
					
						<div class="flex-row">
							<el-form-item label="价格" prop="originalPrice">
								<el-input v-model="form.originalPrice" type="number" placeholder="请输入原价" />
							</el-form-item>
							<!-- <el-form-item label="积分" prop="points">
								<el-input v-model="form.points" type="number" placeholder="请输入积分" />
							</el-form-item> -->
						</div>
						<div class="flex-row">
							<!-- <el-form-item label="会员价" prop="vipPrice">
								<el-input v-model="form.preferentialPrice" type="number" placeholder="请输入会员价" />
							</el-form-item> -->
							<!-- <el-form-item label="会员积分" prop="vipPoints">
								<el-input v-model="form.vipPoints" type="number" placeholder="请输入会员积分" />
							</el-form-item> -->
						</div>
					</div>
				</el-card>

				<el-form-item label="封面" prop="imgUrl">
					<ImageUpload :limit='1' ref="ImageUpload"></ImageUpload>
				</el-form-item>
				<el-form-item label="商品详情图" prop="images">
					<ImageUpload :limit='6' ref="images"></ImageUpload>
				</el-form-item>

				<el-form-item label="限购数量" prop="limitedPurchaseQuantity">
					<el-input v-model="form.limitedPurchaseQuantity" type="number" placeholder="请输入限购数量" />
				</el-form-item>
				<el-form-item label="排序" prop="sort">
					<el-input v-model="form.sort" type="number" placeholder="请输入排序" />
				</el-form-item>
				<el-form-item label="描述" prop="description">
					<el-input v-model="form.description" type="textarea" placeholder="描述" />
				</el-form-item>
				<el-form-item label="备注" prop="remark">
					<el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
				</el-form-item>
				<el-form-item label="内容">
					<editor v-model="form.content" :min-height="192" />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import {
	listStore,
	listGoods,
	getGoods,
	delGoods,
	addGoods,
	updateGoods,
	listGoodsCategory,
	shelvesGoods,
} from '@/api/biz/subsidy';

export default {
	name: 'Goods',
	data() {
		return {
			categoryId: [],
			storeList: [],
			props: { label: 'name', value: 'id' },
			articleCategoryList: [],
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// biz_商品管理表格数据
			goodsList: [],
			// 弹出层标题
			title: '',
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 5,
				type: null,
				categoryId: null,
				storeId: null,
				stock: null,
				unit: null,
				originalPrice: null,
				points: null,
				desc: null,
				preferentialPrice: null,
				imgUrl: null,
				img2Url: null,
				sort: null,
				limitedPurchaseQuantity: null,
				videoUrl: null,
				startTime: null,
				endTime: null,
				status: null,
				isShowDetail: null,
				isShowVideo: null,
				content: null,
				soldQuantity: null,
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {},
		};
	},
	created() {
		this.getList();
		this.listGoodsCategory();
		this.listStore();
	},
	activated() {
		this.listGoodsCategory();
		this.listStore();
	},
	methods: {
		// 任务状态修改
		handleStatusChange(row) {
			let text = row.status === '0' ? '上架' : '下架';
			this.$modal
				.confirm('确认要"' + text + row.name + '"吗？')
				.then(function () {
					return shelvesGoods({id:row.id});
				})
				.then(() => {
					this.$modal.msgSuccess(text + '成功');
				})
				.catch(function () {
					row.status = row.status === '0' ? '1' : '0';
				});
		},
		remoteMethod(query) {
			if (query !== '') {
				this.loading = true;
				const params = {
					name: query,
					pageSize: 10,
				};
				listStore(params).then((response) => {
					this.storeList = response.rows;
					this.loading = false;
				});
			} else {
				this.storeList = [];
			}
		},
		listStore(params) {
			listStore({
				pageSize: 10,
			}).then((response) => {
				this.storeList = response.rows;
			});
		},
		handleChange(value) {
			console.log(value);
		},
		/** 查询biz_分类管理列表 */
		listGoodsCategory() {
			listGoodsCategory({
				pageSize: 100,
			}).then((response) => {
				this.articleCategoryList = response.rows;
			});
		},
		/** 查询biz_商品管理列表 */
		getList() {
			this.loading = true;
			listGoods(this.queryParams).then((response) => {
				this.goodsList = response.rows;
				this.total = response.total;
				this.loading = false;
			});
		},
		// 取消按钮
		cancel() {
			this.open = false;
			this.reset();
		},
		// 表单重置
		reset() {
			this.form = {
				id: null,
				type: null,
				categoryId: null,
				storeId: null,
				stock: null,
				unit: null,
				originalPrice: null,
				points: null,
				desc: null,
				preferentialPrice: null,
				imgUrl: null,
				img2Url: null,
				sort: null,
				limitedPurchaseQuantity: null,
				videoUrl: null,
				startTime: null,
				endTime: null,
				status: 0,
				isShowDetail: null,
				isShowVideo: null,
				content: null,
				soldQuantity: null,
				createByName: null,
				createById: null,
				createTime: null,
				updateByName: null,
				updateById: null,
				updateTime: null,
				isDeleted: null,
				remark: null,
			};
			this.resetForm('form');
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1;
			this.queryParams.categoryId =
				this.categoryId[this.categoryId.length - 1];
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm('queryForm');
			this.categoryId = [];

			this.handleQuery();
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map((item) => item.id);
			this.single = selection.length !== 1;
			this.multiple = !selection.length;
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset();
			this.open = true;
			this.title = '添加biz_商品管理';
			this.$refs.ImageUpload.fileList = [];
			this.$refs.images.fileList = [];
		},
		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset();
			const id = row.id || this.ids;
			this.title = '修改biz_商品管理';
			this.open = true;
			getGoods(id).then((response) => {
				this.$refs.ImageUpload.fileList = [
					{
						url:
							response.data.imgUrl &&
							response.data.imgUrl.indexOf('http') == -1
								? this.$store.state.app.imgUrl +
								  response.data.imgUrl
								: response.data.imgUrl,
						uploadUrl: response.data.imgUrl,
					},
				];
				if (response.data.images) {
					var img = response.data.images.split(',');
					img.forEach((item, index) => {
						img[index] = {
							url:
								item && item.indexOf('http') == -1
									? this.$store.state.app.imgUrl + item
									: item,
							uploadUrl: item,
						};
					});
					console.log(333, img);

					this.$refs.images.fileList = img;
				} else {
					this.$refs.images.fileList = [];
				}
				this.form = response.data;
			});
		},
		/** 提交按钮 */
		submitForm() {
			var form = JSON.parse(JSON.stringify(this.form));
			if (this.$refs.ImageUpload.fileList.length) {
				var fileList = this.$refs.ImageUpload.fileList[0];
				form.imgUrl = fileList.uploadUrl;
			}
			if (this.$refs.images.fileList.length) {
				var images = [];
				this.$refs.images.fileList.forEach((item, index) => {
					images.push(item.uploadUrl);
				});
				form.images = images.join();
			}
			console.log(form);
			if (typeof form.categoryId == 'object') {
				form.categoryPath = form.categoryId.join('|');
				form.categoryId = form.categoryId[form.categoryId.length - 1];
			}
			this.$refs['form'].validate((valid) => {
				if (valid) {
					if (this.form.id != null) {
						updateGoods(form).then((response) => {
							this.$modal.msgSuccess('修改成功');
							this.open = false;
							this.getList();
						});
					} else {
						addGoods(form).then((response) => {
							this.$modal.msgSuccess('新增成功');
							this.open = false;
							this.getList();
						});
					}
				}
			});
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const ids = row.id || this.ids;
			this.$modal
				.confirm(
					'是否确认删除biz_商品管理编号为"' + ids + '"的数据项？'
				)
				.then(function () {
					return delGoods(ids);
				})
				.then(() => {
					this.getList();
					this.$modal.msgSuccess('删除成功');
				})
				.catch(() => {});
		},
		/** 导出按钮操作 */
		handleExport() {
			this.download(
				'/biz/subsidyGoods/export',
				{
					...this.queryParams,
				},
				`goods_${new Date().getTime()}.xlsx`
			);
		},
	},
};
</script>
